import { useEffect } from 'react';

import { useRequest } from 'ahooks';
import { Button, Form, Input, Radio } from 'antd';
import { observer } from 'mobx-react-lite';

import { useStore } from '@/store';

import { emailValidator, mobileValidator } from '@/config/rule';
import { Gender } from '@/enum';
import { orgUserInfoUpdateBySelf } from '@/services/base/yonghuguanlixitongyonghujiekou';

import Avatar from './avatar';

const Page: React.FC = () => {
  const [form] = Form.useForm();
  const store = useStore();
  const submit = useRequest(
    async (values) => {
      await orgUserInfoUpdateBySelf(values);

      store.app?.message.success('修改成功');

      store.getUserInfoByToken(localStorage.getItem('token')!);
    },
    {
      manual: true
    }
  );

  useEffect(() => {
    form.setFieldsValue({
      fullName: store.user?.extendData?.user?.fullName,
      phone: store.user?.extendData?.user?.phone,
      email: store.user?.extendData?.user?.email,
      sex: store.user?.extendData?.user?.sex,
      photoUrl: store.user?.extendData?.user?.photoUrl
    });
  }, [store.user?.extendData?.user, form]);

  return (
    <>
      <Form
        form={form}
        layout="horizontal"
        labelWrap
        labelCol={{ span: 3 }}
        wrapperCol={{ span: 8 }}
        onFinish={submit.run}
        disabled={submit.loading}
      >
        <Form.Item name="photoUrl" label="头像">
          <Avatar />
        </Form.Item>
        <Form.Item name="fullName" label="姓名" rules={[{ required: true, message: '请输入姓名' }]}>
          <Input allowClear />
        </Form.Item>
        <Form.Item
          name="phone"
          label="手机号"
          rules={[{ required: true, message: '请输入手机号' }, { validator: mobileValidator }]}
        >
          <Input allowClear />
        </Form.Item>
        <Form.Item
          name="email"
          label="邮箱"
          rules={[{ required: true, message: '请输入邮箱' }, { validator: emailValidator }]}
        >
          <Input allowClear />
        </Form.Item>
        <Form.Item name="sex" label="性别">
          <Radio.Group>
            <Radio value={Gender['男']}>男</Radio>
            <Radio value={Gender['女']}>女</Radio>
          </Radio.Group>
        </Form.Item>
        <Form.Item wrapperCol={{ offset: 3, span: 8 }}>
          <Button
            loading={submit.loading}
            disabled={submit.loading}
            size="large"
            type="primary"
            htmlType="submit"
            block
          >
            保存
          </Button>
        </Form.Item>
      </Form>
    </>
  );
};

export default observer(Page);
